#include "stdafx.h"
#include "string_manager.h"
#include "config.h"

string_manager string_manager::m_s_sm;

bool string_manager::save_all()
{
	return true;
}

bool string_manager::save_a_file(wstring aStrFileName)
{
	return true;
}

void string_manager::save_a_pair(IXMLDOMNode* aXmlNode, StrStr& aStrStr)
{
	IXMLDOMNamedNodeMap *pAttributes;
		
	aXmlNode->get_attributes( &pAttributes );

	if (pAttributes)
	{
		IXMLDOMNode* pNameNode = NULL;
		IXMLDOMNode* pValueNode = NULL;
		VARIANT name, value;
		pAttributes->getNamedItem(L"name", &pNameNode);
		pAttributes->getNamedItem(L"value", &pValueNode);

		pNameNode->get_nodeValue(&name);
		pValueNode->get_nodeValue(&value);

		aStrStr.insert(make_pair(wstring(name.bstrVal), wstring(value.bstrVal)));

		VariantClear(&value);
		VariantClear(&value);

		pNameNode->Release();
		pValueNode->Release();
		pAttributes->Release();
	}
	return;
}

bool string_manager::load_a_file(wstring aStrFileName, FileNode &fn)
{
	fn.m_strFileName = aStrFileName;

	HRESULT hr;
	IXMLDOMDocument * pXMLDoc;
	IXMLDOMNode * pXDN;
	IXMLDOMNodeList * pNodeList;

	hr = CoCreateInstance(CLSID_DOMDocument30, NULL, CLSCTX_INPROC_SERVER, 
		IID_IXMLDOMDocument, (void**)&pXMLDoc);
	if (FAILED(hr))
	{
		AfxMessageBox(L"fail create xml docment");
		return false;
	}

	//_variant_t fileName 
	VARIANT_BOOL bSuccess = false;
	pXMLDoc->load((_variant_t)aStrFileName.c_str(), &bSuccess);
	if (bSuccess && pXMLDoc->selectSingleNode(L"text", &pXDN) == S_OK)
	{
		if ( SUCCEEDED( pXDN->get_childNodes(&pNodeList) ) )
		{
			long length;
			IXMLDOMNode * pCurrentNode;
			pNodeList->get_length(&length);
			for (int i = 0; i < length; i++)
			{
				pNodeList->get_item(i, &pCurrentNode);

				save_a_pair(pCurrentNode, fn.m_Strs);

				pCurrentNode->Release();
			}
			pNodeList->Release();
		}

		pXMLDoc->Release();
	}else
	{
		return false;
	}

	return true;
}

wstring	string_manager::get_string(wstring aStrName)
{
	wstring fileName = aStrName;
	wstring strName = aStrName;

	int pos = aStrName.find_first_of(L'|');
	if (pos == wstring::npos) return aStrName;
	
	fileName.erase(0, 1);
	fileName.erase(fileName.find_first_of(L'|'));
	strName.erase(0, strName.find_first_of(L'|') + 1);	

	StrStr::iterator str;
	FilePair::iterator file = m_strFiles.find(fileName);
	if (file == m_strFiles.end())
	{
		wstring path;
		FileNode fn;
		path = L"\\string\\gb\\" + fileName + L".xml";
		if (!load_a_file(path_helper::process_file(path), fn)) return aStrName;
		m_strFiles.insert(make_pair(fileName, fn));
		str = fn.m_Strs.find(strName);
		if (str != fn.m_Strs.end())
		{
			return str->second;
		}
	}else
	{
		str = file->second.m_Strs.find(strName);
		if (str != file->second.m_Strs.end())
		{
			return str->second;
		}
	}

	return aStrName;
}